package
{

	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.ui.Mouse;

	[SWF(frameRate="30", width="700", height="500")]
	public class Main extends Sprite
	{
		public function Main()
		{
			if (this.stage)
			{
				onAddedToStageHandler( null );
			}
			else
			{
				this.addEventListener( Event.ADDED_TO_STAGE, onAddedToStageHandler );
			}
		}

		private function onAddedToStageHandler(event:Event):void
		{
			this.removeEventListener( Event.ADDED_TO_STAGE, onAddedToStageHandler );
			this.addEventListener( Event.REMOVED_FROM_STAGE, onRemoveFromStageHandler );

			_infoTF = new TextField();
			_infoTF.x = 20;
			_infoTF.y = 20;
			_infoTF.textColor = 0xFF00FF;
			_infoTF.width = 100;
			_infoTF.height = 20;
			_infoTF.text = "0/0";
			addChild( _infoTF );
			_infoTF.visible = false;

			_sceneRes = new Scene_Skin();
			_sceneRes.x = 700 * 0.5;
			_sceneRes.y = 500 * 0.5;
			addChild( _sceneRes );

			initRes();

			startGame();
		}

		private function startGame():void
		{
			Mouse.hide();
			this.addEventListener( Event.ENTER_FRAME, onEnterFrameHandler );
		}

		private function onEnterFrameHandler(event:Event):void
		{
			for each ( var hole:HolePoint in _holes )
			{
				hole.update();
			}

			_cursor.x = _sceneRes.mouseX - _cursor.width * 0.5;
			_cursor.y = _sceneRes.mouseY - _cursor.height * 0.5;
			_sceneRes.addChild( _cursor );
		}

		private function initRes():void
		{
			_holes = new Vector.<HolePoint>();
			for ( var i:int=0, len:int=_sceneRes.numChildren-1; i<len; i++ )
			{
				_holes.push( new HolePoint( _sceneRes["hole"+i], _infoTF ));
			}
			_cursor = _sceneRes["cursor"];
			_cursor.stop();
			_cursor.cacheAsBitmap = true;
			_cursor.mouseChildren = _cursor.mouseEnabled = false;
		}

		private function onRemoveFromStageHandler(event:Event):void
		{
			Mouse.show();
			this.removeEventListener( Event.ENTER_FRAME, onEnterFrameHandler );
//			_sceneRes.removeEventListener( MouseEvent.MOUSE_MOVE, onMouseMoveHandler );

			for each ( var hole:HolePoint in _holes )
			{
				hole.dispose();
			}

			_sceneRes.removeChildren();

			removeChild( _sceneRes );

			removeChild( _infoTF );
		}

		private var _holes:Vector.<HolePoint>;

		private var _sceneRes:Scene_Skin;

		private var _cursor:MovieClip;

		private var _infoTF:TextField;
	}
}
